package cn.xz.zysjz.utils;

import android.content.Context;
import android.content.SharedPreferences;

import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonParser;

import java.util.ArrayList;
import java.util.Objects;

import cn.xz.zysjz.base.BaseApplication;
import cn.xz.zysjz.bean.CommonLib;

/**
 * APP内部存储封装方法-SharedPreferences存储*/
public class SessionUtils {

    private static SharedPreferences sharedPreferences;

    private static SharedPreferences.Editor editor;

    //初始化，每次判断一下是否已经创建
    private static void initialize(){
        if (sharedPreferences == null){
            sharedPreferences = BaseApplication.getContext().getSharedPreferences(
                    CommonLib.JC_SP_KEY,
                    Context.MODE_PRIVATE
            );
            editor = sharedPreferences.edit();
        }
    }

    //存储字符串
    public static void commitString(String key,String value){
        initialize();
        editor.putString(key, value);
        editor.commit();
    }

    //存储布尔类型
    public static void commitBoolean(String key,Boolean value){
        initialize();
        editor.putBoolean(key, value);
        editor.commit();
    }

    //存储数值类型
    public static void commitInt(String key,int value){
        initialize();
        editor.putInt(key, value);
        editor.commit();
    }

    //存储列表
    public static <T> void commitList(String key, ArrayList<T> value){
        initialize();
        Gson gson = new Gson();
        String mS = gson.toJson(value);
        editor.putString(key, mS);
        editor.commit();
    }

    //获取字符串
    public static String getString(String key,String value){
        initialize();
        String mS = "";
        String mR = sharedPreferences.getString(key,value);
        if (mR != null){
            mS = mR;
        }
        return mS;
    }

    //获取布尔类型
    public static Boolean getBoolean(String key,Boolean value){
        initialize();
        return sharedPreferences.getBoolean(key,value);
    }

    //获取数值类型
    public static int getInt(String key,int value){
        initialize();
        return sharedPreferences.getInt(key,value);
    }

    //获取列表
    public static <T> ArrayList<T> getList(String key,Class<T> mC){
        initialize();
        ArrayList<T> mL = new ArrayList<>();
        String string = getString(key, "");
        if (!Objects.equals(string, "")){
            Gson gson = new Gson();
            JsonArray myList = new JsonParser().parse(string).getAsJsonArray();
            for (JsonElement jsonElement : myList) {
                mL.add(gson.fromJson(jsonElement, mC));
            }
        }
        return mL;
    }
}
